/* eslint-disable react/jsx-no-bind */
/* eslint-disable max-lines-per-function */
import React, {useState, useEffect} from 'react';
import {withRouter} from 'react-router-dom';
import {AccountBookOutlined} from '@ant-design/icons';
import {Form} from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import {Button, message, Table, Row, Col, DatePicker, Select, Tooltip, Popconfirm} from 'antd';
import moment from 'moment';
import {advSearch, getDept, getChannel, deleteAdv, advDownload} from '~/service/sales';
import popUpContainer from '~/utils/common/popupFix';
import './advStyl';
import format from './format';

const {RangePicker} = DatePicker;
const {Option} = Select;
function AdvList(props) {
    const {
        form: {
            getFieldDecorator,
            validateFields,
            setFieldsValue,
            resetFields,
        },
    } = props;

    const [department, setDepartment] = useState();
    const [depList, setDepList] = useState([]);
    const [channelList, setChannelList] = useState([]);
    const [loading, setLoading] = useState(false);
    const [searchList, setSearchList] = useState([]);
    const [allCount, setAllCount] = useState();
    const [allPrice, setAllPrice] = useState();
    const columns = [
        {
            title: '学部',
            width: 100,
            dataIndex: 'department',
            key: 'department',
        },
        {
            title: '投放渠道',
            width: 100,
            dataIndex: 'channel',
            key: 'channel',
        },
        {
            title: '投放时间',
            width: 170,
            dataIndex: 'advBeginTime',
            key: 'advBeginTime',
            render(value) {
                return moment(value, format.dateFormat).format('YYYY-MM-DD HH:00');
            }
        },
        {
            title: '投放截止时间',
            width: 170,
            dataIndex: 'advEndTime',
            key: 'advEndTime',
            render(value) {
                return moment(value, format.dateFormat).format('YYYY-MM-DD HH:00');
            }
        },
        {
            title: '群类别',
            width: 120,
            dataIndex: 'chatroomCategoryList',
            key: 'chatroomCategoryList',
            render(text, record) {
                return (
                    <Tooltip title={text}>
                        <span title={text} className="spanEllipsis">
                            {text}
                        </span>
                    </Tooltip>
                );
            }
        },
        {
            title: '投放金额',
            width: 100,
            dataIndex: 'advPrice',
            key: 'advPrice',
        },
        {
            title: '计入成本',
            width: 100,
            dataIndex: 'canCost',
            key: 'canCost',
        },
        {
            title: '入群人数',
            width: 100,
            dataIndex: 'chatroomNum',
            key: 'chatroomNum',
        },
        {
            title: '留存人数',
            width: 100,
            dataIndex: 'retainUserNum',
            key: 'retainUserNum',
        },
        {
            title: '退群人数',
            width: 100,
            dataIndex: 'quitUserNum',
            key: 'quitUserNum',
        },
        {
            title: '退群率',
            width: 100,
            dataIndex: 'quitUserRate',
            key: 'quitUserRate',
        },
        {
            title: '单用户成本',
            width: 110,
            dataIndex: 'singleCost',
            key: 'singleCost',
        },
        {
            title: '操作',
            key: 'operation',
            fixed: 'right',
            width: 140,
            render(text, record) {
                return (
                    <>
                        <Button
                            size="small"
                            className="editBtn"
                            onClick={() => {
                                props.history.push(`/sales/haoke/create?type=edit&id=${record.id}`);
                            }}
                        >
                            编辑
                        </Button>
                        <Popconfirm
                            title="确定要删除吗?"
                            onConfirm={() => {
                                deleteOne(record.id);
                            }}
                            okText="确定"
                            cancelText="取消"
                        >
                            <Button
                                size="small"
                                onClick={() => {}}
                            >
                                删除
                            </Button>
                        </Popconfirm>
                    </>
                );
            },
        },
    ];

    useEffect(() => {
        getDept().then(res => {
            res && setDepList(res.data.departmentList);
        });
        handleSearch();
    }, []);

    useEffect(() => {
        if (department) {
            getChannel(department).then(res => {
                res && setChannelList(res.data.channelList);
            });
        }
        resetFields(['channel']);
    }, [department]);

    function deleteOne(id) {
        deleteAdv({id}).then(() => {
            handleSearch();
        })
            .catch(errObj => {
                message.error(errObj.msg);
            });
    }

    function handleSearch(e) {
        e && e.preventDefault();
        setLoading(true);
        const param = processSearchParam();

        advSearch(param).then(res => {
            setSearchList(res.data.advertisingResultList);
            setLoading(false);

            if (res.data.summarySource.length > 0) {
                setAllCount(res.data.summarySource[0].allCount);
                setAllPrice(res.data.summarySource[0].allPrice);
            }
        })
            .catch(error => {
                setLoading(false);
                message.error(error.msg);
            });

    }

    // 参数处理逻辑
    function processSearchParam() {
        const param = {};
        validateFields((errObj, values) => {
            if (!errObj) {
                if (values.department) {
                    param.department = values.department;
                }
                if (values.channel) {
                    param.channel = values.channel;
                }
                if (values.canCost) {
                    param.canCost = values.canCost;
                }

                if (values.advEndTime && values.advEndTime.length > 0) {
                    param.advEndTime = [
                        values.advEndTime[0].startOf('day').format('YYYY-MM-DD HH:mm'),
                        values.advEndTime[1].endOf('day').format('YYYY-MM-DD HH:mm')
                    ];
                }
            }
        });

        return param;
    }

    function handleReset() {
        resetFields();
        handleSearch();
    }

    function createNew() {
        props.history.push('/sales/haoke/create');
    }

    function download() {
        const param = processSearchParam();
        advDownload(param, '投放列表');
    }

    return (
        <div className="advList">
            <div className="newLayer">
                <Button type="primary" onClick={createNew}>
                    <AccountBookOutlined />
                    投放填报
                </Button>
                <span>群人数、单用户成本等数据会在填写的投放截止时间1小时后计算得到，请耐心等待！</span>
            </div>
            <div className="searchArea">
                <Form onSubmit={handleSearch}>
                    <Row gutter={24} type="flex" align="middle">
                        <Col span={8}>
                            <Form.Item label="投放截止日期">
                                {getFieldDecorator('advEndTime', {
                                    initialValues: []
                                })(
                                    <RangePicker
                                        style={{
                                            width: '100%'
                                        }}
                                        showTime={false}
                                        format="YYYY-MM-DD"
                                    />
                                )}
                            </Form.Item>
                        </Col>
                        <Col span={8}>
                            <Form.Item label="学部">
                                {
                                    getFieldDecorator('department', {
                                        initialValues: ''
                                    })(
                                        <Select
                                            placeholder="请选择学部"
                                            onChange={setDepartment}
                                            getPopupContainer={popUpContainer}
                                            allowClear
                                        >
                                            {
                                                depList.map(item => (
                                                    <Option key={item} value={item} title={item}>
                                                        {item}
                                                    </Option>
                                                ))
                                            }
                                        </Select>
                                    )
                                }
                            </Form.Item>
                        </Col>
                        <Col span={8}>
                            <Form.Item label="投放渠道">
                                {
                                    getFieldDecorator('channel', {
                                        initialValues: ''
                                    })(
                                        <Select
                                            placeholder="请选择投放渠道"
                                            getPopupContainer={popUpContainer}
                                            allowClear
                                        >
                                            {
                                                channelList.map(item => (
                                                    <Option key={item.name} value={item.name}>
                                                        {item.name}
                                                    </Option>
                                                ))
                                            }
                                        </Select>
                                    )
                                }
                            </Form.Item>
                        </Col>
                        <Col span={8}>
                            <Form.Item label="是否计入成本">
                                {
                                    getFieldDecorator('canCost', {
                                        initialValues: ''
                                    })(
                                        <Select
                                            placeholder="请选择"
                                            getPopupContainer={popUpContainer}
                                            allowClear
                                        >
                                            <Option value={1}>是</Option>
                                            <Option value={2}>否</Option>
                                        </Select>
                                    )
                                }
                            </Form.Item>
                        </Col>
                        <Col span={8} />
                        <Col span={8} style={{textAlign: 'right'}}>
                            <Button type="primary" htmlType="submit" loading={loading}>查询</Button>
                            <Button style={{marginLeft: 8}} onClick={handleReset}>重置</Button>
                        </Col>
                    </Row>
                </Form>
            </div>
            <div className="dataArea">
                <div className="func">
                    <div className="preCount">
                        已填写
                        <span>
                            {allCount}
                        </span>
                        项 | 总投放价格
                        <span>
                            {allPrice}
                            元
                        </span>
                    </div>
                    <Button type="primary" onClick={handleSearch}>刷新数据</Button>
                    <Button onClick={download}>导出</Button>
                </div>
                <Table
                    rowKey="id"
                    columns={columns}
                    dataSource={searchList}
                    scroll={{x: columns.length * 115}}
                    pagination={{
                        showQuickJumper: true,
                        total: searchList.length,
                        showSizeChanger: true
                    }}
                />
            </div>
        </div>
    );
}

export default Form.create({name: 'advSearch'})(withRouter(AdvList));
